package com.isp.common.web.excel;

import com.alibaba.excel.annotation.ExcelProperty;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.groups.Default;
import java.lang.reflect.Field;
import java.util.*;

/**
 * EasyExcel字段校验
 *
 * @author linsy
 * @created 2024/09/26
 */
public class EasyExcelValidHelper {

    private EasyExcelValidHelper() {
    }

    /**
     * 校验实体
     *
     * @param obj 实体
     * @param <T> 实体类型
     * @return 响应
     * @throws Exception 异常
     */
    public static <T> String validateEntity(T obj) throws Exception {
        StringBuilder result = new StringBuilder();
        try (ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory()) {
            Validator validator = validatorFactory.getValidator();
            Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
            if (set != null && !set.isEmpty()) {
                for (ConstraintViolation<T> cv : set) {
                    Optional<Field> fieldOptional = getAllFields(obj.getClass())
                            .stream().filter(i -> cv.getPropertyPath().toString().equals(i.getName())).findAny();
                    if (fieldOptional.isPresent()) {
                        Field declaredField = fieldOptional.get();
                        ExcelProperty annotation = declaredField.getAnnotation(ExcelProperty.class);
                        //拼接错误信息，包含当前出错数据的标题名字+错误信息
                        result.append(annotation.value()[0]).append(cv.getMessage()).append(";");
                    } else {
                        throw new RuntimeException("系统异常");
                    }
                }
            }
        }

        return result.toString();
    }

    /**
     * 获取本类及其父类的属性
     *
     * @param clazz 当前类对象
     * @return 字段数组
     */
    private static List<Field> getAllFields(Class<?> clazz) {
        List<Field> fieldList = new ArrayList<>();
        while (clazz != null) {
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        return fieldList;
    }
}